package com.yorge.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

@Slf4j
public class PreZuulFilter extends ZuulFilter {
    // 定义为过滤器类型为 pre
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    // 设置执行顺序，越小越先执行
    @Override
    public int filterOrder() {
        return 0;
    }
    // 设置是否执行
    @Override
    public boolean shouldFilter() {
        return true;
    }
    // 过滤器具体逻辑
    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取Request
        HttpServletRequest request = ctx.getRequest();
        //获取请求参数accessToken
        String accessToken = request.getHeader("accessToken");

        //使用String工具类
        if (StringUtils.isBlank(accessToken)) {
            log.warn("accessToken is empty");
            ctx.setSendZuulResponse(false);  //进行拦截
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("accessToken is empty");
            } catch (Exception e) {
                log.info(e.getMessage());
            }
            return null;
        }
        log.info("access is ok");
        return null;
    }
}
